package xml;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

public class Main {

	public static void main(String[] args) throws IOException, JDOMException {
		int inputCount = 5;
		
		File xmlFile = null;
		
		System.out.println("XML Datei:");
		
        String filename = null, xpathExpression = null;

        byte[] buffer = new byte[255];
        
		while (xmlFile == null) {
			if (inputCount <= 0)
				break;
			
			System.in.read(buffer);
			
			inputCount--;		
			
			filename = new String(buffer).trim();
			
			if (filename != null) {
				xmlFile = new File(filename);
			
				if (xmlFile != null && !xmlFile.exists())
					xmlFile = null;
			}
		}
		
		if (xmlFile == null)
			throw new IllegalArgumentException("Failed to get XML File.");
		
		buffer = new byte[255];
		
		System.out.println("XPath Expression:");
		
		while (xpathExpression == null) {
			if (inputCount <= 0)
				break;
			
			System.in.read(buffer);
			
			inputCount--;		
			
			xpathExpression = new String(buffer).trim();
			
			if (xpathExpression != null && xpathExpression.length() == 0)
				xpathExpression = null;
		}
		
		if (xpathExpression == null)
			throw new IllegalArgumentException("Failed to get XPath Expression.");
		
		Document document = null;
		
		SAXBuilder saxBuilder = new SAXBuilder();
		saxBuilder.setValidation(true);
		
		try {		
			document = saxBuilder.build(xmlFile);
		} catch (JDOMException e) {
			e.printStackTrace();
		}
		
		if (document != null) {
			XMLOutputter xmlOutputter = new XMLOutputter();
			
			xmlOutputter.setFormat(Format.getPrettyFormat());
			
			List<Element> nodeList = XPath.selectNodes(document, xpathExpression);
			
			System.out.println("XPath result: ");
	
			xmlOutputter.output(nodeList, System.out);
		}
	}

}
